package top.glkj.hms.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;
import top.glkj.hms.service.CodeService;
import top.glkj.hms.utils.VerificationCode;

import java.time.Duration;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/8/24 18:54
 */
@Service
@Slf4j
public class CodeServiceImpl implements CodeService {
    private final RedisTemplate<String, String> template;

    @Autowired
    public CodeServiceImpl(RedisTemplate<String, String> template) {
        this.template = template;
    }

    /**
     * 获取验证码
     *
     * @return 验证码图片
     */
    @Override
    public VerificationCode getCode(Long id) {
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setBufferedImage(verificationCode.getImageCode());
        template.opsForValue().set(id.toString(), verificationCode.getCode(), Duration.ofSeconds(300));
        verificationCode.setCode("");
        return verificationCode;
    }

    /**
     * 检查验证码
     *
     * @param id   验证码编号
     * @param code 验证码
     * @return 检查结果
     */
    @Override
    public void checkCode(Long id, String code) throws AuthenticationException {
        String codes = template.opsForValue().get(id.toString());
        if (codes != null) {
            template.delete(id.toString());
            VerificationCode.checkCode(code, codes);
        } else {
            throw new VerificationCode.CodeAuthenticationException("验证码过期");
        }
    }
}
